package main

import (
	"fmt"
	"log"
	"time"

	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

type User struct {
	gorm.Model
	Name     string
	Age      uint8
	Birthday time.Time
}

func updateWithSave1(db *gorm.DB) {
	var user User
	result := db.First(&user)
	if result.Error != nil {
		log.Fatalf("record not found: %v\n", result.Error)
	}
	user.Name = "leorunloop"
	user.Age = 28
	saveResult := db.Save(&user)
	if saveResult.Error != nil {
		log.Fatalf("failed sava data")
	}
}

func updateWithSave2(db *gorm.DB) {
	result := db.Save(&User{Name: "Jin", Age: 23})
	if result.Error != nil {
		log.Fatalf("record not found: %v\n", result.Error)
	}

	var user User
	user.ID = 1
	user.Name = "LeoRunLoop"
	user.Age = 18
	result = db.Save(&user)
	if result.Error != nil {
		log.Fatalf("record not found: %v\n", result.Error)
	}
}

func updateWithSingle1(db *gorm.DB) {
	result := db.Model(&User{}).Where("age > ?", 30).Update("age", 30)
	if result.Error != nil {
		log.Fatalf("record not found: %v\n", result.Error)
	}
	var users []User
	result = db.Where("age", 30).Find(&users)
	if result.Error != nil {
		log.Fatalf("record not found: %v\n", result.Error)
	}
	for _, user := range users {
		fmt.Printf("id: %v, name: %v, age: %d\n", user.ID, user.Name, user.Age)
	}
}

func updateWithSingle2(db *gorm.DB) {
	var user User
	result := db.Where("id", 2).Take(&user)
	if result.Error != nil {
		log.Fatalf("record not found: %v\n", result.Error)
	}
	result = db.Model(&user).Update("name", "xxxx")
	if result.Error != nil {
		log.Fatalf("record not found: %v\n", result.Error)
	}
}

func updateWithSingle3(db *gorm.DB) {
	var user User
	result := db.Where("id", 2).Take(&user)
	if result.Error != nil {
		log.Fatalf("record not found: %v\n", result.Error)
	}
	result = db.Model(&user).Where("age > ?", 50).Update("name", "yyyy")
	if result.Error != nil {
		log.Fatalf("update failed: %v\n", result.Error)
	}
}
func main() {
	dsn := "host=localhost port=5432 user=postgres password=123456 dbname=my-gorm-app sslmode=disable TimeZone=Asia/ShangHai"
	db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   "gorm-",
			SingularTable: true,
		},
	})
	if err != nil {
		log.Fatalf("failed connect to database")
	}
	// updateWithSave1(db)
	// updateWithSave2(db)
	// updateWithSingle1(db)
	// updateWithSingle2(db)
	updateWithSingle3(db)
}
